package com.valveinspectionsys.order.activity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.valveinspectionsys.R;
import com.valveinspectionsys.dbhelp.XmlNameHelper;
import com.valveinspectionsys.gridview.ImageSwitcherActivity;
import com.valveinspectionsys.maintain.activity.MaintainBandingActivity;
import com.valveinspectionsys.order.db.OrderDao;
import com.valveinspectionsys.povo.DeviceVo;
import com.valveinspectionsys.povo.SpinnerVo;
import com.valveinspectionsys.util.CHexConver;
import com.valveinspectionsys.util.DateUtil;
import com.valveinspectionsys.util.FileNameUtil;
import com.valveinspectionsys.util.SharedPreferenceUtil;
import com.valveinspectionsys.util.TipHelper;

import android.app.Activity;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.database.Cursor;
import android.location.LocationManager;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.provider.MediaStore.Audio.Media;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

/**
 * 通过读卡添加工程的
 * @author King
 *2013-5-6
 */
public class OrderAddRfidActivity extends Activity implements OnClickListener{
    

    private static final int REQUEST_CODE_TAKE_VIDEO = 2;
    private static final int REQUEST_CODE_TAKE_IMAGE = 1;
    private static final int REQUEST_CODE_TAKE_SOUND = 3;
    private final static int DIALOG = 1;
    public static final int ITEM0 = Menu.FIRST;// 系统值
    public ProgressDialog pd;

    public int OrderID = 0;
   
    public String videopath;
    public boolean isupload = false;
    public String soundpath;
    public String type = "无";
    public String typeName="无";//类型名称
    public Button button1;// 读卡
    
    public Button button3;// 保存存
    public EditText edit1;// 名称
    public EditText edit2;// 描述
    public Spinner spinner;// 类型
    public Button button4;// 拍照
    public TextView textview1;// 设备编号 
   
    public LocationClient client;
    public Double latitude = 0.0;// 维度
    public Double longitude = 0.0;// 径度
    public SharedPreferenceUtil sp;
    public OrderDao   dao;
    public List<SpinnerVo> spinnerinfo=new ArrayList<SpinnerVo>();
    public boolean isImg=false;
    public FileNameUtil  f=null;
    
    private NfcAdapter mAdapter;
    private PendingIntent mPendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;
 
    private boolean isNfc=false;
    private String RFID;
    private long time;
    public DeviceVo device;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {

	super.onCreate(savedInstanceState);
	setContentView(R.layout.add_report);
	sp = new SharedPreferenceUtil(this);
	dao=new OrderDao(this, sp.getValue(XmlNameHelper.SqliteName));
	
	f=new FileNameUtil();
	init();
	mAdapter = NfcAdapter.getDefaultAdapter(OrderAddRfidActivity.this);
	mPendingIntent = PendingIntent.getActivity(OrderAddRfidActivity.this, 0, new Intent(OrderAddRfidActivity.this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
	try {
	    ndef.addDataType("*/*");
	    mFilters = new IntentFilter[] { ndef, };
	    mTechLists = new String[][] { new String[] { NfcV.class.getName() }, new String[] { MifareClassic.class.getName() } };

	} catch (MalformedMimeTypeException e) {
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}
    }

    public void init() {
	OrderID=dao.InsertOrder();
	spinner = (Spinner) findViewById(R.id.report_add_type);
	edit1 = (EditText) findViewById(R.id.report_add_name);
	edit2 = (EditText) findViewById(R.id.report_add_des);
	button1 = (Button) findViewById(R.id.report_add_save);

	button3 = (Button) findViewById(R.id.report_add_modifys);
	button4 = (Button) findViewById(R.id.report_add_upload);
	textview1 = (TextView) findViewById(R.id.report_add_waternumber);
	
	button4.setOnClickListener(this);
	button1.setOnClickListener(this);
	
	button3.setOnClickListener(this);
	// 选择工程类型监听器
	spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

	    @Override
	    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		SpinnerVo s=(SpinnerVo)arg0.getSelectedItem();
		type=s.getKey();
	    }

	    @Override
	    public void onNothingSelected(AdapterView<?> arg0) {
		type = "无";

	    }
	});

	spinnerinfo=dao.queryOrderType();
	
	ArrayAdapter<SpinnerVo> ada = new ArrayAdapter<SpinnerVo>(this, android.R.layout.simple_spinner_item, spinnerinfo);// 放数据
	ada.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	spinner.setAdapter(ada);

    }

    @Override
    public void onClick(View v) {
	if (v.getId() == button3.getId()) {
            if(device==null){
        	Toast.makeText(this, "请先读卡", Toast.LENGTH_SHORT).show();
        	return;
            }
	    if (type.equals("无")||type.equals("0")) {
		Toast.makeText(this, "请选择工程单类型", Toast.LENGTH_SHORT).show();
		return;
	    }
	    if (isImg) {
		showDialog(DIALOG + 1);
	    } else {
		Toast.makeText(this, "这种情况须拍照", Toast.LENGTH_SHORT).show();
		return;
	    }

	
	    
	} else if (button1.getId() == v.getId()) {
	    isNfc=true;
	    time=System.currentTimeMillis();
	    new Thread(){

		@Override
		public void run() {
		  while(isNfc){
		      if(!TextUtils.isEmpty(RFID)){
			 Message msg=myHandler.obtainMessage();
			 msg.what=1;
			 myHandler.sendMessage(msg);
			 isNfc=false;
		      }
		      if(System.currentTimeMillis()-time>10000){
			  Message msg=myHandler.obtainMessage();
				 msg.what=2;
				 myHandler.sendMessage(msg);
				 isNfc=false;
		      }
		      try {
			Thread.sleep(500);
		    } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		    }
		  }
		    super.run();
		}
		
	    }.start();
	} else if (v.getId() == button4.getId()) {
	     Intent intent = new Intent(OrderAddRfidActivity.this, ImageSwitcherActivity.class);
	     intent.putExtra("otherid",OrderID+"" );
	     intent.putExtra("status", "-1");
	     intent.putExtra("devicelistid", "-2");
	    startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);
	}

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

	
	menu.add(0, ITEM0 + 2, 0, "录视频");
	menu.add(0, ITEM0 + 3, 0, "录音");

	menu.findItem(ITEM0 + 1);

	return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

	switch (item.getItemId()) {

	case ITEM0 + 1:
	     Intent intent = new Intent(OrderAddRfidActivity.this, ImageSwitcherActivity.class);
	     intent.putExtra("otherid",OrderID+"" );
	     intent.putExtra("status", "-1");
	     intent.putExtra("devicelistid", "-2");
	    startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE);
	    break;
	case ITEM0 + 2:
	    if(!TextUtils.isEmpty(videopath)){
		f.delectFile(videopath);
	    }
	    videoMethod();
	    break;
	case ITEM0 + 3:
	   if(!TextUtils.isEmpty(soundpath)){
	       f.delectFile(soundpath);
	   }
	    soundRecorderMethod();
	    break;

	default:
	    break;
	}
	return super.onOptionsItemSelected(item);
    }

    // 拍摄视频
    private void videoMethod() {
	Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
	FileNameUtil f = new FileNameUtil();
	videopath = f.SDCardPath("order/video");
	String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".avi";
	videopath=videopath+"/"+fileName;
	File out = new File(videopath);
	
	Uri uri = Uri.fromFile(out);
	intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
	intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
	startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);
    }

    /**
     * 发送短息
     */
    public void sendMSM(String number, String name) {
	Uri smsToUri = Uri.parse("smsto:" + number);
	Intent sendIntent = new Intent(Intent.ACTION_VIEW, smsToUri);

	sendIntent.putExtra("sms_body", "尊敬的" + name + "用户:你的水表已绑定RFID卡");

	startActivity(sendIntent);
	System.out.println("发短息");
    }

    // 录音功能
    private void soundRecorderMethod() {
	Intent intent = new Intent(Media.RECORD_SOUND_ACTION);
	
	startActivityForResult(intent, REQUEST_CODE_TAKE_SOUND);
    }

    // 执行回调函数
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	if (requestCode == REQUEST_CODE_TAKE_VIDEO) {
	    System.out.println("返回视频");
	    if (resultCode == RESULT_OK) {
		   
	    }
	} else if (requestCode == REQUEST_CODE_TAKE_IMAGE) {
	    if (resultCode == RESULT_OK) {
		isImg=true;
	    }
	} else if (requestCode == REQUEST_CODE_TAKE_SOUND) {
	    if (resultCode == RESULT_OK) {
		Uri uriVideo = data.getData();
		Cursor cursor = this.getContentResolver().query(uriVideo, null, null, null, null);
		if (cursor.moveToNext()) {
		    String strVideoPath = cursor.getString(cursor.getColumnIndex("_data"));
		    FileInputStream fin = null;
		    FileOutputStream fout = null;
		    File file = new File(strVideoPath);
		    try {
			fin = new FileInputStream(file);

			FileNameUtil f = new FileNameUtil();
			soundpath = f.SDCardPath("order/sound");
			if (soundpath == null) {
			    Toast.makeText(OrderAddRfidActivity.this, "SD卡不可用", Toast.LENGTH_LONG).show();
			    return;
			}
			String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".amr";
			soundpath = soundpath + "/" + fileName;
			System.out.println(soundpath);
			fout = new FileOutputStream(soundpath);

			byte[] buffer = new byte[1024];
			int bytesRead;
			while ((bytesRead = fin.read(buffer)) > 0) {

			    fout.write(buffer, 0, bytesRead);
			}
			fin.close();
			fout.close();
		    } catch (FileNotFoundException e) {

			e.printStackTrace();
		    } catch (IOException e) {

			e.printStackTrace();
		    } finally {
			file.delete();
		    }

		}
	    }
	}
	super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
	Dialog dialog = null;
	switch (id) {

	case DIALOG + 1:
	    Builder builder1 = new android.app.AlertDialog.Builder(this);
	    // 设置对话框的图标
	    builder1.setIcon(R.drawable.buttondraw);
	    builder1.setTitle("确定添加新的工程单？");
	    builder1.setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {
		    if (TextUtils.isEmpty(type)||type.equals("无")) {
			Toast.makeText(OrderAddRfidActivity.this, "你还没选择类型！", Toast.LENGTH_LONG).show();
			return;
		    }
		    boolean b = save();
		    if (b) {
			Toast.makeText(OrderAddRfidActivity.this, "添加数据成功", Toast.LENGTH_LONG).show();

		    }

		}
	    });
	    builder1.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

		@Override
		public void onClick(DialogInterface dialog, int which) {

		}
	    });
	    // 创建一个单选按钮对话框
	    dialog = builder1.create();
	    break;
	}
	return dialog;
    }

    /**
     * 保存
     * 
     * @return
     */
    public boolean save() {
	boolean b = false;
	
	ContentValues values = new ContentValues();
	values.put("ordername", edit1.getEditableText().toString());
	values.put("desc", edit2.getEditableText().toString());
	values.put("soundpath", soundpath);
	values.put("videopath", videopath);
	values.put("status", "0");
	values.put("latitude", latitude);
	values.put("longitude", longitude);
       values.put("ordertype",type );
       values.put("deviceid", device.getDeviceId());
         if(isImg){
             values.put("isimg", "1");
         }else{
             values.put("isimg", "0");
         }
	b=dao.modifyOrder(values, OrderID+"");
	return b;

    }

    /**
     * 修改
     * 
     * @return
     */
    public boolean modify() {
	return false;
	
    }

    
    
    @Override
    protected void onPause() {

	mAdapter.disableForegroundDispatch(this);

	super.onPause();
    }

    @Override
    protected void onResume() {
	mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);

	super.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
	if (!isNfc) {
	    return;
	}

	if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
	    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
	    for (String tech : tagFromIntent.getTechList()) {
		System.out.println(tech);
	    }
	    time = System.currentTimeMillis();
	    MifareClassic mf = MifareClassic.get(tagFromIntent);
	    if (mf != null) {

		boolean auth = false;
		try {
		    mf.connect();
		    auth = mf.authenticateSectorWithKeyA(0, MifareClassic.KEY_DEFAULT);// 获取第一个扇区权限
		    if (auth) {
			byte[] date = mf.readBlock(0);// 读取block 0
			RFID = CHexConver.bytesToHexStrings(date);
			Message msg = myHandler.obtainMessage();
			msg.what = 1;
			msg.obj = RFID;
			myHandler.sendMessage(msg);
		    }

		} catch (IOException e) {

		    e.printStackTrace();
		} finally {
		    try {
			mf.close();
		    } catch (IOException e) {

			e.printStackTrace();
		    }
		}

	    }
	    NfcV nf = NfcV.get(tagFromIntent);
	    if (nf != null) {
		RFID = CHexConver.bytesToHexStrings(nf.getTag().getId());
		Message msg = myHandler.obtainMessage();
		msg.what = 1;
		msg.obj = RFID;
		myHandler.sendMessage(msg);
	    }

	}

	super.onNewIntent(intent);
    }
    /**
     * 上传更新消息
     */
    Handler myHandler = new Handler() {

	@Override
	public void handleMessage(Message msg) {
	

	    if (msg.what == 2) {
		
	    } else if(msg.what==1) {
		   device=dao.queryDevice(RFID, null);
		   if(device==null){
		       Toast.makeText(OrderAddRfidActivity.this, "此设备未绑定标签或没此设备信息", Toast.LENGTH_SHORT).show();
		       return;
		   }else{
		       textview1.setText(device.getDeviceNumber());
		       latitude=device.getLatitude();
		       longitude=device.getLongitude();
		   }
	    }
	}

    };

   
 

    @Override
    protected void onDestroy() {
	dao.delectOrderNoAdd(OrderID+"");
	dao.close();
	super.onDestroy();
    }
    
    


}
